package org.wappumobileapp;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.thoughtworks.xstream.XStream;

public abstract class BaseActivity extends Activity {
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.item1:
			Intent a = new Intent(getApplicationContext(), Main.class);
			// Make "home" the top activity
			a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(a);
			// End the current activity
			finish();
			return true;
		case R.id.item2:
			startActivity(new Intent(getApplicationContext(),
					GetSuggestion.class));

			/********** If It is the same actvity , what to do? **********/

			return true;
		case R.id.item3:
			startActivity(new Intent(getApplicationContext(),
					SendSuggestion.class));
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	public void imageClick(View view) {
		// Implement image click function
		Intent a = new Intent(getApplication(), Main.class);
		// Make "home" the top activity
		a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(a);
		finish();
		return;
	}

	public void writingHistory(List<Long> ids, String file) {
		XStream xstream = new XStream();
		String idXml = xstream.toXML(ids);
		FileOutputStream fos = null;
		try {
			fos = openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(idXml.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean haveNetworkConnection() {
	    boolean haveConnectedWifi = false;
	    boolean haveConnectedMobile = false;

	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	    for (NetworkInfo ni : netInfo) {
	        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
	            if (ni.isConnected())
	                haveConnectedWifi = true;
	        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
	            if (ni.isConnected())
	                haveConnectedMobile = true;
	    }
	    return haveConnectedWifi || haveConnectedMobile;
	}


}
